// useRecords.ts
import { useState, useEffect, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { recordsApi } from '../api/Api';
import { DeliveryFilter, DeliveryRecord } from '../types';

export function useRecords() {
  const [filter, setFilter] = useState<DeliveryFilter>({
    orderNumber: '',
    serialNumber: '',
    status: 2,
    deliveryDate: '',
  });
  const [filteredRecords, setFilteredRecords] = useState<DeliveryRecord[]>([]);

  const { data: records = [], isLoading, error } = useQuery({
    queryKey: ['records', filter], // 根据filter变化时重新请求
    queryFn: () => recordsApi.getRecords({
      orderNumber: filter.orderNumber,
      serialNumber: filter.serialNumber,
    }),
  });

  const handleFilterChange = useCallback((newFilter: DeliveryFilter) => {
    setFilter(newFilter);
  }, []);

  useEffect(() => {
    const filtered = records.filter((record: DeliveryRecord) => {
      const recordDate = new Date(record.deliveryDate);
      const filterDate = new Date(filter.deliveryDate);
      const isSameDate = !filter.deliveryDate || 
                         (recordDate.getFullYear() === filterDate.getFullYear() &&
                          recordDate.getMonth() === filterDate.getMonth() &&
                          recordDate.getDate() === filterDate.getDate());
  
      const isSameStatus = filter.status === 2 || record.status === filter.status;
  
      return isSameStatus && isSameDate;
    });
  
    // 只有在过滤结果变化时才更新 filteredRecords
    if (JSON.stringify(filtered) !== JSON.stringify(filteredRecords)) {
      setFilteredRecords(filtered);
    }
  }, [filter, records, filteredRecords]);  // 依赖 filteredRecords 防止无限循环
  

  return {
    records: filteredRecords,
    isLoading,
    error,
    filter,
    handleFilterChange,
  };
}
